//package com.kecheng.servermonitor.config.task;
//
//import com.github.benmanes.caffeine.cache.Cache;
//import com.github.benmanes.caffeine.cache.Caffeine;
//import com.kecheng.servermonitor.config.cache.HeartbeatCache;
//import com.kecheng.servermonitor.entity.HeartbeatTime;
//import com.kecheng.servermonitor.service.MailService;
//import lombok.val;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.Resource;
//import java.time.Duration;
//import java.time.Instant;
//import java.time.LocalDateTime;
//import java.time.ZoneId;
//import java.time.format.DateTimeFormatter;
//import java.util.Arrays;
//import java.util.Map;
//import java.util.concurrent.TimeUnit;
//
//@Component
//public class HeartbeatMonitorTask {
//    @Value("${time}")
//    long HEARTBEAT_TIMEOUT_MS; // 超时阈值
//
//    @Resource
//    private HeartbeatCache heartbeatCache;
//
//    @Value("${count}")
//    private int count;
//    @Resource
//    private MailService mailService;
//    // 缓存用于记录每个clientId的发送次数,防止一直发送邮件，60分钟后刷新缓存，如果还有就再次发送报警
//    private final Cache<String, Integer> heartbeatNotificationCache = Caffeine.newBuilder()
//            .expireAfterWrite(60, TimeUnit.MINUTES) // 缓存项60分钟后过期
//            .build();
//
//    @Scheduled(fixedRate = 10 * 1000) // 每10秒检查一次
//    public void checkHeartbeatTimeout() {
//        val heartbeats = heartbeatCache.getAllHeartbeats();
//
//        for (Map.Entry<String, HeartbeatTime> entry : heartbeats.entrySet()) {
//            String clientId = entry.getKey();
//            // 最后发送心跳时间
//            val heartbeatTime = entry.getValue();
//            // 当前时间
//            LocalDateTime now = LocalDateTime.ofInstant(
//                    Instant.ofEpochMilli(System.currentTimeMillis()),
//                    ZoneId.systemDefault());
//            // 计算时间差（秒）
//            long duration = Duration.between(heartbeatTime.getLastHeartbeatTime(), now).getSeconds();
//            if (duration > HEARTBEAT_TIMEOUT_MS) {
//                // 获取当前发送次数，如果没有记录则为0
//                Integer countNow = heartbeatNotificationCache.get(clientId+":heartbeat-count", k -> 1);
//                if (countNow <= count) {
//                    // 发送通知
//                    handleHeartbeatTimeout(clientId, heartbeatTime.getLastHeartbeatTime(), heartbeatTime.getEmail(),countNow);
//                    // 更新发送次数
//                    heartbeatNotificationCache.put(clientId+":heartbeat-count", countNow + 1);
//                }else {
//                    System.out.println(clientId+"心跳监测已发送"+count+"次报警短信！！！");
//                }
//            }
//        }
//    }
//
//    private void handleHeartbeatTimeout(String clientId, LocalDateTime lastHeartbeatTime, String email,Integer countNow) {
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String subject = "【" + clientId + "】心跳超时告警";
//        String body = "客户端【" + clientId + "】已超过"+HEARTBEAT_TIMEOUT_MS/60+"分钟未发送心跳\n" +
//                "最后心跳时间: " + lastHeartbeatTime.format(formatter) + "\n" +
//                "当前时间: " + LocalDateTime.now().format(formatter);
//        // 发送告警邮件
//        mailService.sendAlertMail(Arrays.asList(email.split(",")), subject, body, countNow, clientId);
//
//    }
//}